import { LdrsLoader } from "@renderer/components/business/ldrs-loader";
import { NewVersionModal } from "@renderer/components/business/new-version-modal";
import { Badge } from "@renderer/components/ui/base/badge";
import { Button } from "@renderer/components/ui/base/button";
import { Label } from "@renderer/components/ui/base/field";
import { ProgressCircle } from "@renderer/components/ui/base/progress-circle";
import { Switch } from "@renderer/components/ui/base/switch";
import { useVersionUpdate } from "@renderer/hooks/use-version-update";
import { cn } from "@renderer/lib/utils";
import { useAutoUpdateSetting } from "@renderer/queries/hooks/use-settings";
import type { UpdaterStatus } from "@shared/types/version-updater";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import packageJson from "../../../../../package.json";

const { version } = packageJson;

interface ButtonConfig {
  text: string;
  icon?: React.ReactNode;
  isPending: boolean;
}

export function VersionUpdate() {
  const { t } = useTranslation("translation", {
    keyPrefix: "settings.general-settings.version-update",
  });

  const { data: autoUpdate } = useAutoUpdateSetting();
  const { status, progress, handleChange, handleActions } = useVersionUpdate();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showBadge = ["available", "downloading", "downloaded"].includes(status);

  const getButtonConfig = (
    status: UpdaterStatus,
    progress: number,
  ): ButtonConfig => {
    const configs: Record<UpdaterStatus, ButtonConfig> = {
      checking: {
        text: t("checking"),
        icon: <LdrsLoader type="line-spinner" size={16} />,
        isPending: true,
      },
      available: {
        text: t("update-now"),
        isPending: false,
      },
      downloading: {
        text: t("downloading"),
        icon: <ProgressCircle value={progress} className="size-4" />,
        isPending: true,
      },
      downloaded: {
        text: t("restart-to-update"),
        isPending: false,
      },
      idle: {
        text: t("check-for-updates"),
        isPending: false,
      },
      "not-available": {
        text: t("check-for-updates"),
        isPending: false,
      },
      error: {
        text: t("check-for-updates"),
        isPending: false,
      },
    };

    return configs[status];
  };

  const buttonConfig = getButtonConfig(status, progress);

  return (
    <div className="flex flex-col gap-2">
      <Label className="text-label-fg">{t("label")}</Label>
      {autoUpdate !== undefined && (
        <Switch
          className="h-11 rounded-[10px] bg-setting px-3.5 py-2.5"
          isSelected={autoUpdate}
          onChange={handleChange}
        >
          <Label className="self-center">{t("switch.label")}</Label>
        </Switch>
      )}

      <div className="flex items-center justify-between gap-x-10 rounded-[10px] bg-setting px-3.5 py-1.5">
        <div className="flex flex-row gap-1.5 text-sm">
          <span className="text-setting-fg">{t("version-info")}</span>
          <span className="text-muted-fg">{version}</span>
          <Badge
            intent="success"
            className={cn("text-xs", {
              hidden: !showBadge,
            })}
          >
            {status === "downloaded"
              ? t("new-version-downloaded")
              : t("new-version-available")}
          </Badge>
        </div>
        <div className="flex flex-row space-x-2">
          <Button
            className="h-8 rounded-lg"
            intent="secondary"
            onPress={() => setIsModalOpen(true)}
          >
            🎉 {t("new-version-released.title")} 🎉
          </Button>

          <Button
            className="h-8 rounded-lg"
            onPress={handleActions}
            isPending={buttonConfig.isPending}
          >
            {buttonConfig.icon ? (
              <div className="flex flex-row items-center gap-1.5">
                {buttonConfig.icon}
                <span>{buttonConfig.text}</span>
              </div>
            ) : (
              buttonConfig.text
            )}
          </Button>
        </div>
      </div>

      <NewVersionModal isOpen={isModalOpen} onOpenChange={setIsModalOpen} />
    </div>
  );
}
